import { defineStore } from 'pinia'
import { UserState, UserInfo } from '@/stores/interface'
import piniaPersistConfig from '@/stores/helper/persist'
import { fetchUserinfo } from '@api/login'
export const useUserStore = defineStore({
  id: 'stove-user',
  state: (): UserState => ({
    token: '',
    userInfo: undefined
  }),
  getters: {},
  actions: {
    // Set Token
    async setToken(token: string) {
      this.token = token
    },
    // Set setUserInfo
    setUserInfo(userInfo?: UserInfo) {
      this.userInfo = userInfo
    },
    async getUserInfo() {
      try {
        if (this.userInfo) {
          return this.userInfo
        }
        const { data } = await fetchUserinfo()
        this.userInfo = data
        return this.userInfo
      } catch (e) {
        console.error(e)
        return {}
      }
    }
  },
  persist: piniaPersistConfig('stove-user')
})
